package br.ufrj.dcc.trabxml.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import java.util.TreeMap;

import javax.imageio.ImageIO;


public class TrabUtil {
        

    private static Image img_empty = new BufferedImage(113, 160,
            BufferedImage.TYPE_INT_ARGB);

    public static String formatISBN(String isbn) {
        isbn = isbn.replaceAll("-","").trim();
        if (isbn.length() == 10) {
            isbn = isbn.substring(0, 1) + "-" + isbn.substring(1);
            isbn = isbn.substring(0, 5) + "-" + isbn.substring(5);
            isbn = isbn.substring(0, 11) + "-" + isbn.substring(11);
        } else if (isbn.length() == 13) {
            isbn = isbn.substring(0, 3) + "-" + isbn.substring(3);
            isbn = isbn.substring(0, 5) + "-" + isbn.substring(5);
            isbn = isbn.substring(0, 9) + "-" + isbn.substring(9);
            isbn = isbn.substring(0, 15) + "-" + isbn.substring(15);
        } else {
            isbn = null;
        }
        return isbn;
    }
    
    public static String getStringFromURL(String _url) throws IOException {
        URL url = new URL(_url);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                url.openStream()));
        String xml = "";
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            xml += line;
        }
        return xml;
    }
    
    public static String readTextFile(String filename) {
        String txt = "";
        byte[] buffer = new byte[1024];
        FileInputStream fis;
        try {
            fis = new FileInputStream(filename);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            return "";
        }
        try {
            int nBytes = fis.read(buffer);
            while(nBytes != -1){
                txt += new String(buffer,0,nBytes,"UTF-8");
                nBytes = fis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return txt;
    }

    public static String getGroupHost(int group) {
        if (Integer.toString(group).equals(
                Properties.instance.getProperty("mygroup"))) {
            return "127.0.0.1";
        }
        return Properties.instance.getProperty("group" + group);
    }

    public static int getGroupPort(int group) {
        return Integer
                .parseInt(Properties.instance.getProperty("port" + group));
    }
    
    private static final Map<String, Image> imagesCache = new TreeMap<String,Image>();

    public static Image getBookImage(String isbn) {
        try {            
            isbn = convertFromIsbn13ToIsbn10(isbn);
            Image img = imagesCache.get(isbn);
            if (img != null) {
                return img;
            }
            URL url = new URL("http://images.amazon.com/images/P/"
                    + isbn.replaceAll("-", "") + ".01.MZZZZZZZ.jpg");
            img = ImageIO.read(url);
            if ((img == null || (img.getWidth(null) == 1))) {
                return img_empty;
            }
            imagesCache.put(isbn, img);
            return img;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Converts an EAN or an ISBN 13 to ISBN 10
     * 
     * @param isbn13OrEAN
     * @return String the ISBN 10
     */
    public static String convertFromIsbn13ToIsbn10(String isbn13OrEAN) {
        String isbn10 = "";
        if (isbn13OrEAN == null) {
            return isbn13OrEAN;
        }
        isbn13OrEAN = isbn13OrEAN.replaceAll("-", "");
        if (isbn13OrEAN.length() != 13) {
            return isbn13OrEAN;
        }
        isbn10 = isbn13OrEAN.substring(3, isbn13OrEAN.length() - 1);
        char[] allChars = isbn10.toCharArray();

        int sum = 0;
        for (int i = 0; i < allChars.length; i++) {
            char current = allChars[i];
            int currentNumber = Character.getNumericValue(current);
            if (currentNumber < 0 || currentNumber > 9) {
                throw new IllegalArgumentException("Not valid ISBN");
            }
            sum += currentNumber * (10 - i);
        }
        int modulu = sum % 11;
        int checkDigit = 0;

        if (modulu != 0) {
            checkDigit = 11 - modulu;
        }

        // if the checkDigit is 10 should be x
        if (checkDigit == 10) {
            isbn10 += 'X';
        } else {
            isbn10 += checkDigit;
        }
        return isbn10;
    }

    static {
        Graphics g = img_empty.getGraphics();
        g.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
        g.setColor(Color.BLACK);
        g.drawString("Sem imagem", 17, 80);
        g.drawRect(0, 0, img_empty.getWidth(null) - 1, img_empty
                .getHeight(null) - 1);
    }

}
